package com.szh.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.szh.common.dto.mq.OrderTo;
import com.szh.common.exception.NoStockException;
import com.szh.common.utils.R;
import com.szh.common.vo.MemberResponseVo;
import com.szh.gulimall.order.constant.OrderConstant;
import com.szh.gulimall.order.dao.OrderItemDao;
import com.szh.gulimall.order.entity.OrderItemEntity;
import com.szh.gulimall.order.enume.OrderStatusEnum;
import com.szh.gulimall.order.feign.CartFeignService;
import com.szh.gulimall.order.feign.MemberFeignService;
import com.szh.gulimall.order.feign.ProductFeignService;
import com.szh.gulimall.order.feign.WareFeignService;
import com.szh.gulimall.order.interceptor.LoginUserInterceptor;
import com.szh.gulimall.order.service.OrderItemService;
import com.szh.gulimall.order.to.OrderCreateTo;
import com.szh.gulimall.order.vo.*;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.szh.common.utils.PageUtils;
import com.szh.common.utils.Query;

import com.szh.gulimall.order.dao.OrderDao;
import com.szh.gulimall.order.entity.OrderEntity;
import com.szh.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private ThreadLocal<OrderSubmitVo> orderSubmitVoThreadLocal = new ThreadLocal<>();

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private MemberFeignService memberFeignService;

    @Autowired
    private CartFeignService cartFeignService;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private ThreadPoolExecutor executor;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<>()
        );
        return new PageUtils(page);
    }

    /**
     * 跳转到订单结算页，同时封装页面所需的数据进行返回
     */
    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo = new OrderConfirmVo();
        MemberResponseVo memberResponseVo = LoginUserInterceptor.loginUser.get();
        //获取之前的请求数据
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        CompletableFuture<Void> addressFuture = CompletableFuture.runAsync(() -> {
            //每一个异步线程都来共享之前的请求数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //1.远程调用会员服务，查询某个会员的所有收货地址列表
            //获取登录会员的id，已经保存在了ThreadLocal中
            Long memberId = memberResponseVo.getId();
            List<MemberAddressVo> addresses = memberFeignService.getAddresses(memberId);
            confirmVo.setAddress(addresses);
        }, executor);
        CompletableFuture<Void> cartFuture = CompletableFuture.runAsync(() -> {
            //每一个异步线程都来共享之前的请求数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //2.远程调用购物车服务，查询所有选中的购物项
            List<OrderItemVo> orderItems = cartFeignService.getCurrentUserCartItems();
            confirmVo.setItems(orderItems);
        }, executor).thenRunAsync(() -> {
            List<OrderItemVo> items = confirmVo.getItems();
            List<Long> skuIds = items.stream().map(OrderItemVo::getSkuId).collect(Collectors.toList());
            R res = wareFeignService.getHasSkuStock(skuIds);
            List<SkuStockVo> skuStockVoList = res.getData(new TypeReference<List<SkuStockVo>>() {});
            if (!CollectionUtils.isEmpty(skuStockVoList)) {
                Map<Long, Boolean> stockMap = skuStockVoList.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));
                confirmVo.setStockMap(stockMap);
            }
        });
        //3.查询用户积分
        Integer integration = memberResponseVo.getIntegration();
        confirmVo.setIntegeration(integration);
        //4.订单总金额、应付总金额会自动计算
        //5.防重令牌机制，解决订单提交的接口幂等性问题
        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberResponseVo.getId(),
                token, 30, TimeUnit.MINUTES);
        confirmVo.setOrderToken(token);
        //等待以上异步任务都完成之后，再将封装好的confirmVo返回
        CompletableFuture.allOf(addressFuture, cartFuture).get();
        return confirmVo;
    }

    /**
     * 订单下单
     * @GlobalTransactional: seata处理全局分布式事务注解
     * 订单服务中调用了库存服务，如果订单服务出异常，此注解可保证订单、库存服务都回滚
     */
    @Override
    @Transactional
//    @GlobalTransactional
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {
        MemberResponseVo memberResponseVo = LoginUserInterceptor.loginUser.get();
        SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo();
        responseVo.setCode(0);
        orderSubmitVoThreadLocal.set(vo);
        //1.验证令牌，令牌的验证和删除需要保证原子性操作
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        String orderToken = vo.getOrderToken();
        Long result = redisTemplate.execute(new DefaultRedisScript<>(script, Long.class),
                Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberResponseVo.getId()), orderToken);
        if (result == 0L) { //令牌验证失败
            responseVo.setCode(1);
            return responseVo;
        } else { //令牌验证成功
            //创建订单
            OrderCreateTo order = createOrder();
            //验价
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = vo.getPayPrice();
            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) { //价格比对成功
                //保存订单
                saveOrder(order);
                //锁定库存，只要有异常回滚订单数据
                WareSkuLockVo wareSkuLockVo = new WareSkuLockVo();
                wareSkuLockVo.setOrderSn(order.getOrder().getOrderSn());
                List<OrderItemVo> orderItemVos = order.getOrderItems().stream().map(item -> {
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setSkuId(item.getSkuId());
                    orderItemVo.setCount(item.getSkuQuantity());
                    orderItemVo.setTitle(item.getSpuName());
                    return orderItemVo;
                }).collect(Collectors.toList());
                wareSkuLockVo.setLocks(orderItemVos);
                R res = wareFeignService.orderLockStock(wareSkuLockVo);
                if (res.getCode() == 0) {
                    responseVo.setOrder(order.getOrder());
                    //订单创建完成，向MQ中发送消息
                    rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", order.getOrder());
                    return responseVo;
                } else {
                    String errorMsg = (String) res.get("msg");
                    throw new NoStockException(errorMsg);
                }
            } else { //价格比对不符
                responseVo.setCode(2);
                return responseVo;
            }
        }
    }

    /**
     * 根据订单号查询订单状态
     */
    @Override
    public OrderEntity getOrderStatus(String orderSn) {
        QueryWrapper<OrderEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_sn", orderSn);
        OrderEntity orderEntity = this.getOne(queryWrapper);
        return orderEntity;
    }

    /**
     * 定时关单
     */
    @Override
    public void closeOrder(OrderEntity orderEntity) {
        //查询当前订单的状态，1分钟之后，死信队列接收到了延时队列发来的消息
        //此时只有订单状态是待付款，才需要关单操作
        QueryWrapper<OrderEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_sn", orderEntity.getOrderSn());
        OrderEntity order = this.getOne(queryWrapper);
        if (order.getStatus().equals(OrderStatusEnum.CREATE_NEW.getCode())) {
            OrderEntity entity = new OrderEntity();
            entity.setId(orderEntity.getId());
            entity.setStatus(OrderStatusEnum.CANCELED.getCode());
            this.updateById(entity);
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(order, orderTo);
            try {
                //订单状态改为已取消之后，再向MQ发送消息，发送到库存服务的死信队列中，确保一定执行库存解锁功能
                rabbitTemplate.convertAndSend("order-event-exchange", "order.release.order", orderTo);
            } catch (Exception ex) {

            }
        }
    }

    private void saveOrder(OrderCreateTo order) {
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);
        List<OrderItemEntity> orderItemEntities = order.getOrderItems();
        orderItemService.saveBatch(orderItemEntities);
    }

    private OrderCreateTo createOrder() {
        MemberResponseVo memberResponseVo = LoginUserInterceptor.loginUser.get();
        OrderCreateTo orderCreateTo = new OrderCreateTo();
        //创建订单号
        String orderSn = IdWorker.getTimeId();
        OrderEntity entity = new OrderEntity();
        entity.setOrderSn(orderSn);
        entity.setMemberId(memberResponseVo.getId());
        entity.setMemberUsername(memberResponseVo.getUsername());
        //获取收货地址、收货人、运费信息
        OrderSubmitVo submitVo = orderSubmitVoThreadLocal.get();
        R res = wareFeignService.getFare(submitVo.getAddrId());
        FareVo fareVo = res.getData(new TypeReference<FareVo>(){});
        entity.setFreightAmount(fareVo.getFare());
        entity.setReceiverDetailAddress(fareVo.getAddress().getDetailAddress());
        entity.setReceiverProvince(fareVo.getAddress().getProvince());
        entity.setReceiverCity(fareVo.getAddress().getCity());
        entity.setReceiverRegion(fareVo.getAddress().getRegion());
        entity.setReceiverName(fareVo.getAddress().getName());
        entity.setReceiverPhone(fareVo.getAddress().getPhone());
        entity.setReceiverPostCode(fareVo.getAddress().getPostCode());
        //设置订单状态信息
        entity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        entity.setAutoConfirmDay(7);
        entity.setConfirmStatus(0);
        //构建所有的订单项
        List<OrderItemEntity> orderItemEntities = buildOrderItems(orderSn);
        //计算订单价格、积分相关信息
        computePrice(entity, orderItemEntities);
        orderCreateTo.setOrder(entity);
        orderCreateTo.setOrderItems(orderItemEntities);
        return orderCreateTo;
    }

    /**
     * 计算订单价格相关信息
     */
    private void computePrice(OrderEntity entity, List<OrderItemEntity> orderItemEntities) {
        BigDecimal total = new BigDecimal("0.0");
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal integration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");
        BigDecimal gift = new BigDecimal("0.0");
        BigDecimal growth = new BigDecimal("0.0");
        for (OrderItemEntity itemEntity : orderItemEntities) {
            total = total.add(itemEntity.getRealAmount());
            coupon = coupon.add(itemEntity.getCouponAmount());
            integration = integration.add(itemEntity.getIntegrationAmount());
            promotion = promotion.add(itemEntity.getPromotionAmount());
            gift = gift.add(new BigDecimal(itemEntity.getGiftIntegration().toString()));
            growth = growth.add(new BigDecimal(itemEntity.getGiftGrowth().toString()));
        }
        entity.setTotalAmount(total); //订单总金额
        entity.setPayAmount(total.add(entity.getFreightAmount())); //应付总金额
        entity.setCouponAmount(coupon);
        entity.setIntegrationAmount(integration);
        entity.setPromotionAmount(promotion);
        entity.setIntegration(gift.intValue());
        entity.setGrowth(growth.intValue());
        entity.setDeleteStatus(0);
    }

    /**
     * 构建所有的订单项
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        List<OrderItemVo> currentUserCartItems = cartFeignService.getCurrentUserCartItems();
        if (!CollectionUtils.isEmpty(currentUserCartItems)) {
            List<OrderItemEntity> orderItemEntityList = currentUserCartItems.stream().map(cartItem -> {
                OrderItemEntity itemEntity = buildOrderItem(cartItem);
                itemEntity.setOrderSn(orderSn);
                return itemEntity;
            }).collect(Collectors.toList());
            return orderItemEntityList;
        }
        return null;
    }

    /**
     * 构建某一个订单项
     */
    private OrderItemEntity buildOrderItem(OrderItemVo cartItem) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        //商品的spu信息
        Long skuId = cartItem.getSkuId();
        R res = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo spuInfoVo = res.getData(new TypeReference<SpuInfoVo>(){});
        orderItemEntity.setSpuId(spuInfoVo.getId());
        orderItemEntity.setSpuBrand(spuInfoVo.getBrandId().toString());
        orderItemEntity.setCategoryId(spuInfoVo.getCatalogId());
        orderItemEntity.setSpuName(spuInfoVo.getSpuName());
        //商品的sku信息
        orderItemEntity.setSkuId(cartItem.getSkuId());
        orderItemEntity.setSkuName(cartItem.getTitle());
        orderItemEntity.setSkuPic(cartItem.getImage());
        orderItemEntity.setSkuPrice(cartItem.getPrice());
        orderItemEntity.setSkuQuantity(cartItem.getCount());
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
        orderItemEntity.setSkuAttrsVals(skuAttr);
        //积分、成长值信息
        orderItemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        orderItemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        //优惠、价格信息
        orderItemEntity.setPromotionAmount(new BigDecimal("0"));
        orderItemEntity.setCouponAmount(new BigDecimal("0"));
        orderItemEntity.setIntegrationAmount(new BigDecimal("0"));
        BigDecimal totalPrice = orderItemEntity.getSkuPrice().multiply(new BigDecimal(String.valueOf(orderItemEntity.getSkuQuantity())));
        BigDecimal resultPrice = totalPrice.subtract(orderItemEntity.getPromotionAmount())
                .subtract(orderItemEntity.getCouponAmount())
                .subtract(orderItemEntity.getIntegrationAmount());
        orderItemEntity.setRealAmount(resultPrice);
        return orderItemEntity;
    }
}